import { Component, OnInit } from '@angular/core';
import { AbstractControl, FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Store } from '@ngxs/store';
import { UserAction } from '../../../store/user';
import { NzModalRef } from 'ng-zorro-antd/modal';
import { SystemAction } from '../../../store';

@Component({
  selector: 'app-password-modal',
  templateUrl: './password-modal.component.html',
  styleUrls: ['./password-modal.component.scss'],
})
export class PasswordModalComponent implements OnInit {
  validateForm: FormGroup;

  constructor(
      private store: Store,
      private fb: FormBuilder,
      private modal: NzModalRef,
  ) {
    this.validateForm = this.fb.group({
      old: ['', [Validators.required]],
      new: ['', [Validators.required]],
      confirm: ['', [Validators.required, this.checkConfirm()]],
    });
  }

  ngOnInit(): void {
  }

  submitForm() {
    this.store.dispatch(new UserAction.ChangePassword()).subscribe(() => {
      this.modal.destroy();
      this.store.dispatch(new SystemAction.Logout());
    });
  }

  updateConfirmValidator(): void {
    Promise.resolve().then(() => this.validateForm.controls['confirm'].updateValueAndValidity());
  }

  private checkConfirm() {
    return (control: AbstractControl) => {
      if (!control.value || !this.validateForm.get('new')?.getRawValue()) {
        return null;
      }
      return control.value === this.validateForm.get('new')?.getRawValue() ? null : {confirm: true};
    };
  }
}
